package com.sddnytsh.body_buildingsystem.components

import android.graphics.drawable.Icon
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ChatBubble
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.filled.Person
import androidx.compose.material.icons.filled.Send
import androidx.compose.material.icons.filled.ThumbUp
import androidx.compose.material.icons.outlined.ChatBubble
import androidx.compose.material.icons.outlined.Favorite
import androidx.compose.material.icons.outlined.ThumbUp
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.sddnytsh.body_buildingsystem.topic.CommunityPost
import com.sddnytsh.body_buildingsystem.topic.Comment
import com.sddnytsh.body_buildingsystem.data.state.UserState
import com.sddnytsh.body_buildingsystem.config.NetworkConfig
import com.sddnytsh.body_buildingsystem.network.CommunityApiService
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.MediaType.Companion.toMediaType
import com.google.gson.Gson
import com.google.firebase.crashlytics.buildtools.reloc.com.google.common.reflect.TypeToken
import com.sddnytsh.body_buildingsystem.R
import com.sddnytsh.body_buildingsystem.components.SimpleAvatarImage
import com.sddnytsh.body_buildingsystem.components.DefaultAvatar
import java.io.IOException

@Composable
fun PostItem(
    post: CommunityPost,
    onPostClick: (CommunityPost) -> Unit,
    onLikeClick: (CommunityPost) -> Unit,
    onFavoriteClick: (CommunityPost) -> Unit,
    onCommentClick: (CommunityPost) -> Unit
) {
    // 定义颜色方案
    val primaryColor = Color(0xFF4361EE)
    val secondaryColor = Color(0xFF3A0CA3)
    val accentColor = Color(0xFFF72585)
    val successColor = Color(0xFF4CAF50)
    val warningColor = Color(0xFFFFC107)
    val cardColor = Color.White
    val textPrimary = Color(0xFF212529)
    val textSecondary = Color(0xFF6C757D)
    val lightBackground = Color(0xFFF8F9FA)

    // 本地状态
    var isLiked by remember { mutableStateOf(post.isLiked) }
    var isFavorited by remember { mutableStateOf(post.isFavorited) }
    var likeCount by remember { mutableStateOf(post.likeCount) }
    var favoriteCount by remember { mutableStateOf(post.favoriteCount) }
    var commentCount by remember { mutableStateOf(post.commentCount) }
    var showComments by remember { mutableStateOf(false) }

    // 初始化时加载评论数量
    LaunchedEffect(post.id) {
        try {
            val currentUserId = UserState.currentUserId
            val comments = getCommentsByPostId(post.id.toInt(), currentUserId)
            commentCount = comments.size
        } catch (e: Exception) {
            // 如果加载失败，保持原来的数量
        }
    }

    Card(
        modifier = Modifier
            .fillMaxWidth()
            .clickable { onPostClick(post) },
        shape = RoundedCornerShape(16.dp),
        colors = CardDefaults.cardColors(containerColor = cardColor),
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
    ) {
        Column(
            modifier = Modifier.padding(20.dp)
        ) {
            // 头像行
            Row(
                verticalAlignment = Alignment.CenterVertically,
                modifier = Modifier.fillMaxWidth()
            ) {
                // 用户头像 - 优先使用当前用户头像，否则使用帖子作者头像
                val currentUserId = UserState.currentUserId
                val displayAvatar = if (post.userId == currentUserId && UserState.currentUserAvatar != null) {
                    UserState.currentUserAvatar
                } else {
                    post.authorAvatar
                }
                
                if (displayAvatar != null && displayAvatar.isNotEmpty()) {
                    SimpleAvatarImage(
                        avatarUrl = displayAvatar,
                        fallbackName = post.author ?: "未知用户",
                        size = 44.dp
                    )
                } else {
                    DefaultAvatar(
                        name = post.author ?: "未知用户",
                        size = 44.dp
                    )
                }

                Spacer(modifier = Modifier.width(12.dp))

                Column(
                    modifier = Modifier.weight(1f)
                ) {
                    Text(
                        text = post.author ?: "匿名用户",
                        style = MaterialTheme.typography.bodyLarge.copy(
                            fontWeight = FontWeight.SemiBold,
                            color = textPrimary
                        )
                    )
                    Text(
                        text = post.createdAt ?: "刚刚",
                        style = MaterialTheme.typography.bodySmall.copy(
                            color = textSecondary
                        )
                    )
                }
            }

            Spacer(modifier = Modifier.height(16.dp))

            // 帖子标题
            if (!post.title.isNullOrBlank()) {
                Text(
                    text = post.title ?: "无标题",
                    style = MaterialTheme.typography.titleMedium.copy(
                        fontWeight = FontWeight.Bold,
                        color = textPrimary
                    ),
                    modifier = Modifier.fillMaxWidth()
                )
                Spacer(modifier = Modifier.height(8.dp))
            }

            // 帖子内容
            Text(
                text = post.content ?: "无内容",
                style = MaterialTheme.typography.bodyMedium.copy(
                    color = textPrimary,
                    lineHeight = 22.sp
                ),
                modifier = Modifier.fillMaxWidth()
            )

            Spacer(modifier = Modifier.height(20.dp))

            // 互动按钮行
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceAround
            ) {
                // 点赞按钮
                InteractionButton(
                    icon = if (isLiked) Icons.Filled.ThumbUp else Icons.Outlined.ThumbUp,
                    count = likeCount,
                    isActive = isLiked,
                    activeColor = accentColor,
                    inactiveColor = textSecondary,
                    label = "点赞",
                    onClick = {
                        val currentUserId = UserState.currentUserId
                        if (currentUserId != null) {
                            CoroutineScope(Dispatchers.IO).launch {
                                try {
                                    val apiService = CommunityApiService()
                                    val result = apiService.togglePostLike(currentUserId, post.id)
                                    result.onSuccess { data ->
                                        withContext(Dispatchers.Main) {
                                            isLiked = !isLiked
                                            likeCount = if (isLiked) likeCount + 1 else likeCount - 1
                                            onLikeClick(post)
                                        }
                                    }
                                } catch (e: Exception) {
                                    // 处理错误
                                }
                            }
                        }
                    }
                )

                // 收藏按钮
                InteractionButton(
                    icon = if (isFavorited) Icons.Filled.Favorite else Icons.Outlined.Favorite,
                    count = favoriteCount,
                    isActive = isFavorited,
                    activeColor = warningColor,
                    inactiveColor = textSecondary,
                    label = "收藏",
                    onClick = {
                        val currentUserId = UserState.currentUserId
                        if (currentUserId != null) {
                            CoroutineScope(Dispatchers.IO).launch {
                                try {
                                    val apiService = CommunityApiService()
                                    val result = apiService.togglePostFavorite(currentUserId, post.id)
                                    result.onSuccess { data ->
                                        withContext(Dispatchers.Main) {
                                            isFavorited = !isFavorited
                                            favoriteCount = if (isFavorited) favoriteCount + 1 else favoriteCount - 1
                                            onFavoriteClick(post)
                                        }
                                    }
                                } catch (e: Exception) {
                                    // 处理错误
                                }
                            }
                        }
                    }
                )

                // 评论按钮
                InteractionButton(
                    icon = Icons.Default.ChatBubble,
                    count = commentCount,
                    isActive = showComments,
                    activeColor = primaryColor,
                    inactiveColor = textSecondary,
                    label = "评论",
                    onClick = {
                        showComments = !showComments
                        if (showComments) {
                            onCommentClick(post)
                        }
                    }
                )
            }

            // 评论区域
            if (showComments) {
                Spacer(modifier = Modifier.height(16.dp))
                CommentSection(
                    post = post, 
                    primaryColor = primaryColor,
                    onCommentCountUpdate = { count -> commentCount = count }
                )
            }
        }
    }
}

// 互动按钮组件
@Composable
fun InteractionButton(
    icon: ImageVector,
    count: Int,
    isActive: Boolean,
    activeColor: Color,
    inactiveColor: Color,
    label: String,
    onClick: () -> Unit
) {
    val color = if (isActive) activeColor else inactiveColor

    TextButton(
        onClick = onClick,
        colors = ButtonDefaults.textButtonColors(
            contentColor = color
        ),
        modifier = Modifier.height(40.dp)
    ) {
        Row(
            verticalAlignment = Alignment.CenterVertically
        ) {
            Icon(
                imageVector = icon,
                contentDescription = label,
                modifier = Modifier.size(20.dp)
            )
            Spacer(modifier = Modifier.width(4.dp))
            Text(
                text = count.toString(),
                style = MaterialTheme.typography.bodyMedium.copy(
                    fontWeight = if (isActive) FontWeight.Bold else FontWeight.Normal
                )
            )
        }
    }
}

// 评论区域组件
@Composable
fun CommentSection(
    post: CommunityPost, 
    primaryColor: Color,
    onCommentCountUpdate: (Int) -> Unit
) {
    var comments by remember { mutableStateOf<List<Comment>>(emptyList()) }
    var isLoading by remember { mutableStateOf(false) }
    var newComment by remember { mutableStateOf("") }

    val textPrimary = Color(0xFF212529)
    val textSecondary = Color(0xFF6C757D)
    val lightBackground = Color(0xFFF8F9FA)

    // 加载评论
    LaunchedEffect(post.id) {
        isLoading = true
        try {
            val currentUserId = UserState.currentUserId
            comments = getCommentsByPostId(post.id.toInt(), currentUserId)
            onCommentCountUpdate(comments.size)
        } catch (e: Exception) {
            // 处理错误
        } finally {
            isLoading = false
        }
    }

    Column {
        // 评论标题
        Text(
            text = "评论 (${comments.size})",
            style = MaterialTheme.typography.titleSmall.copy(
                fontWeight = FontWeight.SemiBold,
                color = textPrimary
            ),
            modifier = Modifier.padding(vertical = 8.dp)
        )

        // 评论输入框
        Card(
            modifier = Modifier.fillMaxWidth(),
            shape = RoundedCornerShape(12.dp),
            colors = CardDefaults.cardColors(containerColor = lightBackground)
        ) {
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(12.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                OutlinedTextField(
                    value = newComment,
                    onValueChange = { newComment = it },
                    modifier = Modifier.weight(1f),
                    placeholder = { Text("写一条评论...", color = textSecondary.copy(alpha = 0.6f)) },
                    singleLine = true,
                    shape = RoundedCornerShape(8.dp)
                )

                Spacer(modifier = Modifier.width(8.dp))

                IconButton(
                    onClick = {
                        if (newComment.isNotBlank()) {
                            val currentUserId = UserState.currentUserId
                            if (currentUserId != null) {
                                CoroutineScope(Dispatchers.IO).launch {
                                    try {
                                        val response = addComment(post.id.toInt(), newComment, currentUserId)
                                        if (response.success) {
                                            withContext(Dispatchers.Main) {
                                                comments = getCommentsByPostId(post.id.toInt(), currentUserId)
                                                onCommentCountUpdate(comments.size)
                                                newComment = ""
                                            }
                                        }
                                    } catch (e: Exception) {
                                        // 处理错误
                                    }
                                }
                            }
                        }
                    },
                    enabled = newComment.isNotBlank(),
                    modifier = Modifier.size(40.dp)
                ) {
                    Icon(
                        imageVector = Icons.Default.Send,
                        contentDescription = "发送评论",
                        tint = if (newComment.isNotBlank()) primaryColor else textSecondary.copy(alpha = 0.4f)
                    )
                }
            }
        }

        Spacer(modifier = Modifier.height(12.dp))

        // 评论列表
        if (isLoading) {
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(80.dp),
                contentAlignment = Alignment.Center
            ) {
                CircularProgressIndicator(
                    modifier = Modifier.size(24.dp),
                    color = primaryColor,
                    strokeWidth = 2.dp
                )
            }
        } else if (comments.isEmpty()) {
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(80.dp),
                contentAlignment = Alignment.Center
            ) {
                Text(
                    text = "暂无评论，快来发表第一条评论吧~",
                    color = textSecondary.copy(alpha = 0.6f),
                    style = MaterialTheme.typography.bodySmall
                )
            }
        } else {
            LazyColumn(
                modifier = Modifier.heightIn(max = 200.dp),
                verticalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                items(items = comments) { comment ->
                    CommentItem(
                        comment = comment, 
                        primaryColor = primaryColor,
                        onCommentLikeUpdate = { commentId, isLiked, likeCount ->
                            // 更新评论列表中的对应评论
                            comments = comments.map { c ->
                                if (c.id == commentId) {
                                    c.copy(isLiked = isLiked, likeCount = likeCount)
                                } else {
                                    c
                                }
                            }
                        }
                    )
                }
            }
        }
    }
}

// 评论项组件
@Composable
fun CommentItem(
    comment: Comment, 
    primaryColor: Color,
    onCommentLikeUpdate: (Long, Boolean, Int) -> Unit = { _, _, _ -> }
) {
    val textPrimary = Color(0xFF212529)
    val textSecondary = Color(0xFF6C757D)
    val lightBackground = Color(0xFFF8F9FA)
    
    // 评论点赞状态
    var isLiked by remember { mutableStateOf(comment.isLiked) }
    var likeCount by remember { mutableStateOf(comment.likeCount) }

    Card(
        modifier = Modifier.fillMaxWidth(),
        shape = RoundedCornerShape(12.dp),
        colors = CardDefaults.cardColors(containerColor = lightBackground),
        elevation = CardDefaults.cardElevation(defaultElevation = 1.dp)
    ) {
        Column(
            modifier = Modifier.padding(12.dp)
        ) {
            // 评论头部
            Row(
                verticalAlignment = Alignment.CenterVertically
            ) {
                Box(
                    modifier = Modifier
                        .size(32.dp)
                        .clip(CircleShape)
                        .background(primaryColor.copy(alpha = 0.1f)),
                    contentAlignment = Alignment.Center
                ) {
                    Icon(
                        imageVector = Icons.Default.Person,
                        contentDescription = "用户头像",
                        tint = primaryColor,
                        modifier = Modifier.size(16.dp)
                    )
                }

                Spacer(modifier = Modifier.width(8.dp))

                Column(
                    modifier = Modifier.weight(1f)
                ) {
                    Text(
                        text = comment.author ?: "匿名用户",
                        style = MaterialTheme.typography.bodySmall.copy(
                            fontWeight = FontWeight.Medium,
                            color = textPrimary
                        )
                    )
                    Text(
                        text = comment.createdAt ?: "",
                        style = MaterialTheme.typography.bodySmall.copy(
                            color = textSecondary.copy(alpha = 0.6f)
                        )
                    )
                }

                // 点赞按钮
                IconButton(
                    onClick = {
                        val currentUserId = UserState.currentUserId
                        if (currentUserId != null) {
                            CoroutineScope(Dispatchers.IO).launch {
                                try {
                                    val apiService = CommunityApiService()
                                    val result = apiService.toggleCommentLike(currentUserId, comment.id)
                                    result.onSuccess { data: Map<String, Any> ->
                                        withContext(Dispatchers.Main) {
                                            isLiked = !isLiked
                                            likeCount = if (isLiked) likeCount + 1 else likeCount - 1
                                            onCommentLikeUpdate(comment.id, isLiked, likeCount)
                                        }
                                    }
                                } catch (e: Exception) {
                                    // 处理错误
                                }
                            }
                        }
                    },
                    modifier = Modifier.size(24.dp)
                ) {
                    Icon(
                        imageVector = if (isLiked) Icons.Filled.ThumbUp else Icons.Outlined.ThumbUp,
                        contentDescription = "点赞评论",
                        tint = if (isLiked) primaryColor else textSecondary.copy(alpha = 0.6f),
                        modifier = Modifier.size(16.dp)
                    )
                }
            }

            Spacer(modifier = Modifier.height(8.dp))

            // 评论内容
            Text(
                text = comment.content,
                style = MaterialTheme.typography.bodyMedium.copy(
                    color = textPrimary,
                    lineHeight = 18.sp
                )
            )

            Spacer(modifier = Modifier.height(4.dp))

            // 评论底部
            Row(
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = "${likeCount} 赞",
                    style = MaterialTheme.typography.bodySmall.copy(
                        color = textSecondary.copy(alpha = 0.6f)
                    )
                )
            }
        }
    }
}

// 获取评论列表的函数
suspend fun getCommentsByPostId(postId: Int, currentUserId: Long? = null): List<Comment> {
    data class CommentApiResponse<T>(
        val success: Boolean,
        val data: T
    )
    
    data class NestedData(
        val comments: List<Map<String, Any>>
    )

    return withContext(Dispatchers.IO) {
        val url = if (currentUserId != null) {
            "${NetworkConfig.BASE_URL}/api/post-comments/post/$postId?currentUserId=$currentUserId"
        } else {
            "${NetworkConfig.BASE_URL}/api/post-comments/post/$postId"
        }

        val client = OkHttpClient.Builder()
            .connectTimeout(5, java.util.concurrent.TimeUnit.SECONDS)
            .readTimeout(8, java.util.concurrent.TimeUnit.SECONDS)
            .writeTimeout(5, java.util.concurrent.TimeUnit.SECONDS)
            .retryOnConnectionFailure(true)
            .connectionPool(okhttp3.ConnectionPool(5, 5, java.util.concurrent.TimeUnit.MINUTES))
            .build()
        val request = Request.Builder()
            .url(url)
            .build()

        client.newCall(request).execute().use { response ->
            if (!response.isSuccessful) {
                throw IOException("Unexpected code $response")
            }

            val responseBody = response.body?.string()
            val gson = Gson()
            val apiResp: CommentApiResponse<NestedData> = gson.fromJson(
                responseBody,
                object : TypeToken<CommentApiResponse<NestedData>>() {}.type
            )
            if (apiResp.success) {
                // 将Map转换为Comment对象
                apiResp.data.comments.map { commentMap ->
                    Comment(
                        id = (commentMap["id"] as? Number)?.toLong() ?: 0L,
                        postId = (commentMap["postId"] as? Number)?.toLong() ?: 0L,
                        userId = (commentMap["userId"] as? Number)?.toLong() ?: 0L,
                        content = commentMap["content"] as? String ?: "",
                        likeCount = (commentMap["likeCount"] as? Number)?.toInt() ?: 0,
                        isLiked = commentMap["isLiked"] as? Boolean ?: false,
                        createdAt = commentMap["createdAt"] as? String ?: "",
                        author = commentMap["author"] as? String ?: "匿名用户",
                        parentId = (commentMap["parentId"] as? Number)?.toLong(),
                        rootId = (commentMap["rootId"] as? Number)?.toLong(),
                        isDeleted = commentMap["isDeleted"] as? Boolean ?: false
                    )
                }
            } else {
                emptyList()
            }
        }
    }
}

// 发送评论的函数
suspend fun addComment(postId: Int, content: String, userId: Long): CommentAddResponse {
    data class CommentRequest(
        val postId: Long,
        val userId: Long,
        val content: String
    )

    return withContext(Dispatchers.IO) {
        val url = "${NetworkConfig.BASE_URL}/api/post-comments"

        // 创建请求体
        val commentRequest = CommentRequest(postId.toLong(), userId, content)
        val gson = Gson()
        val requestBody = gson.toJson(commentRequest).toRequestBody("application/json".toMediaType())

        val client = OkHttpClient.Builder()
            .connectTimeout(5, java.util.concurrent.TimeUnit.SECONDS)
            .readTimeout(8, java.util.concurrent.TimeUnit.SECONDS)
            .writeTimeout(5, java.util.concurrent.TimeUnit.SECONDS)
            .retryOnConnectionFailure(true)
            .connectionPool(okhttp3.ConnectionPool(5, 5, java.util.concurrent.TimeUnit.MINUTES))
            .build()
        val request = Request.Builder()
            .url(url)
            .post(requestBody)
            .addHeader("Content-Type", "application/json")
            .build()

        client.newCall(request).execute().use { response ->
            if (!response.isSuccessful) {
                throw IOException("Unexpected code $response")
            }

            val responseBody = response.body?.string()
            gson.fromJson(responseBody, CommentAddResponse::class.java)
        }
    }
}

// API响应数据类
data class CommentAddResponse(val success: Boolean, val message: String? = null)
